<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入活动名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开始时间" prop="beginDate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.beginDate" type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.endDate" type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否上线" prop="isShow">
        <el-select v-model="queryParams.isShow" placeholder="请选择是否上线" clearable size="small">
          <el-option v-for="dict in isShowOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否开奖" prop="isAward">
        <el-select v-model="queryParams.isAward" placeholder="请选择是否开奖" clearable size="small">
          <el-option v-for="dict in isAwardOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['StarActivity:StarActivity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['StarActivity:StarActivity:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['StarActivity:StarActivity:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['StarActivity:StarActivity:export']">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" border stripe :data="StarActivityList" @selection-change="handleSelectionChange"
      :header-cell-style="{'text-align':'center'}">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键id" align="center" prop="id" /> -->
      <el-table-column label="活动名称" align="center" prop="name" width="160" :show-overflow-tooltip="true"/>
      <el-table-column label="开始时间" align="center" prop="beginDate" width="160" />
      <el-table-column label="结束时间" align="center" prop="endDate" width="160" />
      <el-table-column label="是否上线" align="center" prop="isShow" :formatter="isShowFormat" width="80" />
      <el-table-column label="是否开奖" align="center" prop="isAward" :formatter="isAwardFormat" width="80" />
      <el-table-column label="开奖时间" align="center" prop="awardTime" width="160" />
      <el-table-column label="活动内容" align="center" prop="content" width="160" :show-overflow-tooltip="true" />
      <el-table-column label="视频地址" align="center" prop="showUrl" width="160" :show-overflow-tooltip="true" />
      <!-- <el-table-column label="视频地址" prop="showUrl">
        <template slot-scope="scope">
          <div v-if="scope.row.showUrl" class="showUrl" @click="winOpen(scope.row.showUrl)">{{scope.row.showUrl}}</div>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="参与人员" align="center" prop="joinUser" :show-overflow-tooltip="true" /> -->
      <el-table-column label="创建人" align="center" prop="createdBy" width="100" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['StarActivity:StarActivity:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['StarActivity:StarActivity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改星选官活动管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body center :before-close="cancel"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item v-if="!form.id" label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item v-if="form.id" label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item> -->
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker clearable size="small" style="width: 200px" v-model="form.beginDate" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker clearable size="small" style="width: 200px" v-model="form.endDate" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开奖时间" prop="awardTime">
              <el-date-picker clearable size="small" style="width: 200px" v-model="form.awardTime" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开奖时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否上线">
              <el-select v-model="form.isShow" placeholder="请选择是否上线">
                <el-option v-for="dict in isShowOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否开奖">
              <el-select v-model="form.isAward" placeholder="请选择是否开奖">
                <el-option v-for="dict in isAwardOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入活动内容" />
        </el-form-item>
        <el-form-item label="视频地址" prop="showUrl">
          <el-input v-model="form.showUrl" disabled="disabled" placeholder="请上传视频" />
          <el-upload ref="upload" :action="uploadUrl" :headers="uploadHeaders" :show-file-list="false" :on-success="handleVideoSuccess"
            :on-progress="uploadVideoProcess" accept="video/mp4,video/ogg,video/flv,video/avi,video/wmv,video/rmvb"
            :before-upload="beforeUploadVideo" class="video-uploader">
            <el-button type="primary" plain icon="el-icon-file" size="mini">上传视频</el-button>
          </el-upload>
          <el-button v-if="form.showUrl" type="success" plain icon="el-icon-file" size="mini" @click="winOpen()">查看视频</el-button>
          <el-button v-if="form.showUrl" type="info" plain size="mini" @click="clearShowUrl()">重置视频地址</el-button>
        </el-form-item>
        <el-form-item v-if="videoFlag == true" label="上传进度">
          <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:30px;"></el-progress>
        </el-form-item>
        <el-form-item label="参与人员" prop="joinUser">
          <el-input v-model="form.joinUser" type="textarea" :rows="4" placeholder="输入格式如 '张**  185****8888,李**  199****7777'" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listStarActivity,
    getStarActivity,
    delStarActivity,
    addStarActivity,
    updateStarActivity,
    exportStarActivity
  } from "@/api/StarActivity/StarActivity";
  import {
    getToken,
    getLesseeId
  } from '@/utils/auth'

  export default {
    name: "StarActivity",
    data() {
      return {
        uploadUrl: '',
        videoUploadPercent: 0, // 视频上传进度
        videoFlag: false,
        uploadHeaders: {
          Authorization: '',
          lesseeId: ''
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 星选官活动管理表格数据
        StarActivityList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否上线字典
        isShowOptions: [],
        // 是否开奖字典
        isAwardOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: undefined,
          beginDate: undefined,
          endDate: undefined,
          isShow: undefined,
          isAward: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        // startDatePicker: {},
        // endDatePicker: {},
        // awardTimePicker: {}
      };
    },
    created() {
      // var that = this;
      // this.startDatePicker.disabledDate = function(time) {
      //   return time.getTime() < (Date.now() - 8.64e7);
      // };
      // this.endDatePicker.disabledDate = function(time) {
      //   if (that.form.beginDate) {
      //     const startDate = new Date(that.form.beginDate);
      //     return time < startDate;
      //   } else {
      //     return time.getTime() < (Date.now() - 8.64e7);
      //   }
      // };
      // this.awardTimePicker.disabledDate = function(time) {
      //   // if (that.form.beginDate && that.form.endDate) {
      //   //   const startDate = new Date(that.form.beginDate);
      //   //   const stopDate = new Date(that.form.endDate);
      //   //   return (time < startDate) || (time > stopDate);
      //   // } else {
      //   return time.getTime() < (Date.now() - 8.64e7);
      //   // }
      // };
      if (process.env.NODE_ENV === 'development') {
        this.uploadUrl = 'http://wx.4006002222.com/hifapitest/common/upload/hnxxgVideo';
      } else {
        this.uploadUrl = document.domain + '/hifapi/common/upload/hnxxgVideo';
      }
      this.uploadHeaders = {
        Authorization: ('Bearer ' + getToken()),
        lesseeId: getLesseeId()
      };
      console.log('查看process.env.VUE_APP_BASE_API：');
      console.log(process.env);
      console.log('视频上传接口：' + this.uploadUrl);
      console.log(this.uploadHeaders);
      this.getList();
      this.getDicts("sys_yes_no").then(response => {
        this.isShowOptions = response.data;
      });
      this.getDicts("sys_yes_no").then(response => {
        this.isAwardOptions = response.data;
      });
    },
    methods: {
      handleVideoSuccess(res, file) { //获取上传图片地址
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        console.log('上传结果');
        console.log(res);
        if (res.code == 200) {
          this.form.showUrl = res.url;
        } else {
          this.$message.error('视频上传失败，请重新上传！');
        }
      },
      beforeUploadVideo(file) {
        const isLt50M = file.size / 1024 / 1024 < 50;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) == -1) {
          this.$message.error('请上传正确的视频格式');
          return false;
        }
        if (!isLt50M) {
          this.$message.error('视频' + (file.size / 1024 / 1024) + 'MB, 超过50MB！请另选视频!');
          return false;
        }
      },
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = Number(file.percentage.toFixed(0));
      },
      winOpen() {
        if (!this.form.showUrl) {
          return;
        }
        window.open(this.form.showUrl, "_blank");
      },
      clearShowUrl() {
        this.form.showUrl = '';
      },
      /** 查询星选官活动管理列表 */
      getList() {
        this.loading = true;
        listStarActivity(this.queryParams).then(response => {
          this.StarActivityList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 是否上线字典翻译
      isShowFormat(row, column) {
        return this.selectDictLabel(this.isShowOptions, row.isShow);
      },
      // 是否开奖字典翻译
      isAwardFormat(row, column) {
        return this.selectDictLabel(this.isAwardOptions, row.isAward);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          createdBy: undefined,
          createdTime: undefined,
          updatedBy: undefined,
          updatedTime: undefined,
          isActive: undefined,
          lesseeId: undefined,
          name: undefined,
          beginDate: undefined,
          endDate: undefined,
          isShow: undefined,
          isAward: undefined,
          awardTime: undefined,
          content: undefined,
          showUrl: undefined,
          joinUser: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加星选官活动管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        var that = this;
        this.reset();
        const id = row.id || this.ids
        getStarActivity(id).then(response => {
          var row = response.data;
          if (row.beginDate && (row.beginDate.length === 10)) {
            row.beginDate = row.beginDate + ' 00:00:00';
          }
          if (row.endDate && (row.endDate.length === 10)) {
            row.endDate = row.endDate + ' 00:00:00';
          }
          if (row.awardTime && (row.awardTime.length === 10)) {
            row.awardTime = row.awardTime + ' 00:00:00';
          }
          this.form = row;
          console.log(this.form);
          this.open = true;
          this.title = "修改星选官活动管理";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateStarActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addStarActivity(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除星选官活动管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStarActivity(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有星选官活动管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStarActivity(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>
<style>
  .el-tooltip__popper {
    max-width: 800px;
  }

  .showUrl:hover {
    cursor: pointer;
  }

  .video-uploader {
    display: inline-block;
    margin-right: 15px;
  }
</style>
